package odgs.message.server;

import java.util.HashMap;
import java.util.List;

import odgs.Connection;
import odgs.Contents;
import odgs.ContentsFile;
import odgs.Result;
import odgs.message.Message;
import odgs.message.MessageHandler;
import odgs.message.MessageProcessor;
import odgs.transaction.ExecuteTransction;

public class ExecuteTransactionRequestHandler implements MessageHandler 
{
	public void execute(MessageProcessor processor, Message msg, Connection con)
	{
		boolean canGetContents = true;
		int result = 0;
		ExecuteTransction tran = (ExecuteTransction) msg.get("transaction");
		List<ContentsFile> files = processor.getServerManager().getContentsFile((Contents)tran.getSource());

		if(files.size() == 0)
		{
			canGetContents = false;
			result = Result.CONTENTS_FILE_NOT_EXIST;
		}

		for (ContentsFile file : files)
		{
			if(!processor.getServerManager().isConnected(file.getNodeId()))
			{
				canGetContents = false;
				result = Result.CONTENTS_USER_NOT_CONNECTED;
				break;
			}
		}
		
		Message reMsg = new Message(Message.CONTENTS_EXECUTE_TRANSACTION_RESPONSE);
		if(canGetContents)
		{
			for (ContentsFile file : files)
			{
				String ip = processor.getServerManager().getIP(file.getNodeId());
				if(ip == null)
				{
					canGetContents = false;
					break;
				}
				file.setIp(ip);
			}

			processor.getServerManager().lockContents(tran.getSource());
			reMsg.put("files", files);
			reMsg.put("transaction",tran);
		}
		else
		{
			reMsg.put("transaction",tran);
			reMsg.setResult(Result.CONTENTS_GET_FAIL);
		}
		con.sendMessage(reMsg);
	}
}
